#!/usr/bin/ruby
# fdirs - find all directories
# To change this template, choose Tools | Templates
# and open the template in the editor.
require 'rubygems'
require 'net/sftp'

#various globally used variables
i=1   #counter
thehost = "192.168.197.103" #ipad's IP address
uname = "root"  #should always be root
pword = "" #default pword is "alpine"... please change it if you haven't already
ipad_path = "/private/var/mobile/Media/DCIM/100APPLE" #directory on the ipad to which you want to copy said pictures

puts "\n\n\n"
puts "jpeg to iPad v1.0a"
puts "\n"

def helpme
  puts "automatically converts jpg's to"
  #
end

def dieinfire(msg)
  puts "\n\n"
  puts "Error encountered:"
  puts msg
  puts "exiting app"
  puts "\n\n"
  exit 0
end






#Net::SFTP.start(host, username, :password => password) do |sftp|

Net::SFTP.start(thehost, uname, :password => pword)  do |sftp|
  sftp.dir.foreach(ipad_path) do |f|
    #puts f.name
    n = f.name.to_s.scan(/0*(\d+)\.JPG/i).to_s
    if n
      #puts n
      d = i.to_i
      if n.to_i > d
        i = n
      end
      #puts i
    end
      
    
  end


  #debug
  #dieinfire("i=#{i}\ngot past connecting to host")
  #

  dir = Dir.open(".")
  list = dir.entries.grep(/(\.jpg)/i)

  list.empty? ? dieinfire("No jpg's in current directory") : 0
  system("mkdir tmp")

  a = 0
  list.each do |file|
    i = i.to_i + 1
    # do something with dirname/file
    outfile = "IMG_%04d.JPG" %i.to_i
    #puts "#{file} is file \##{i}"
    system("cp '#{file}' tmp/#{outfile}")
    sftp.upload!("tmp/#{outfile}", ipad_path + "/#{outfile}")
    puts "successfully uploaded #{file} to #{outfile} on your iPad"

    a = a + 1
  end

  puts "#{a-1} file(s) copied to tmp directory."


end
